/**
 * 获取学生列表
 * 
 * /admin/student/getlist
 */

const User_info = require('../../../models/usersInfo')
const utils = require('../../../utils/index')
const Sequelize = require('sequelize')
const Op = Sequelize.Op
const $ = require('../../../utils/common')

const get_student_list = async function (req, res) {
    try{
        var query = {}
        // 学生表和教师表合并在一起了
        query['user_role'] = 'student'
        if (req.query.user_name) { 
            query['user_name'] = req.query.user_name
        }
        var user_name  = {}
        if (req.query.user_name) {
            user_name['[Op.like]'] = '%' + req.query.user_name + '%'
        }
        if (req.query.user_fullname) {query['user_fullname'] = req.query.user_fullname}
        if (req.query.user_class) {query['user_class'] = req.query.user_class}
        if (req.query.user_major) {query['user_major'] = req.query.user_major}

        var offset = 1
        var limit = parseInt(req.query.size)
        if (req.query.page > 1) {
            offset = parseInt(req.query.size) * (parseInt(req.query.page) - 1)
        } else if (req.query.page == 1) {
            offset = 0
        }
        
        // 模糊搜索
        const sql_res = await User_info.findAndCountAll({
            offset: offset,
            limit: limit,
            where: {
                user_role: 'student',
                user_name: {
                    [Op.like]: '%' + (query.user_name == undefined ? '' : query.user_name) + '%'
                },
                user_fullname: {
                    [Op.like]: '%' + (query.user_fullname == undefined ? '' : query.user_fullname) + '%'
                },
                user_class: {
                    [Op.like]: '%' + (query.user_class == undefined ? '' : query.user_class) + '%'
                },
                user_major: {
                    [Op.like]: '%' + (query.user_major == undefined ? '' : query.user_major) + '%'
                }
            },
            attributes: ['id', 'user_name', 'user_fullname', 'user_major', 'user_address',  'user_phone', 'user_role', 'user_status'],
        })
        
        res.json({
            code: 200,
            message: 'success',
            data: {
                list: sql_res.rows,
                total: sql_res.count
            }
        })

        // 日志
        utils.create_a_log(req, '学生列表', '浏览')
        return
    }

    catch(err) {
        $.sendMessage(res, 0000, 'err: '+ err)
        utils.create_a_log(req, '学生列表', '浏览', '失败')
        return
    }
}
    
module.exports = get_student_list